package com.bsj.pay.controller.admin;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.bsj.pay.common.Result;
import com.bsj.pay.config.GlobalConfig;
import com.bsj.pay.model.AccountBean;
import com.bsj.pay.model.ChargeAccountBean;
import com.bsj.pay.model.OrderBean;
import com.bsj.pay.service.AccountService;
import com.bsj.pay.service.ChargeAccountService;
import com.bsj.pay.service.LogService;
import com.bsj.pay.service.MerchantService;
import com.bsj.pay.service.OrderService;
import com.bsj.pay.service.PartnerService;
import com.bsj.pay.service.impl.OrderServiceImpl;
import com.bsj.pay.util.ResultUtil;
import com.bsj.pay.util.SpringUtil;
import com.bsj.pay.util.platform.PlatformInterface;
import com.github.pagehelper.PageInfo;

@RequestMapping("/admin/order")
@Controller("adminOrderController")
public class OrderController {
	
	@Autowired
	private OrderService orderService;
	
	@Autowired
	private MerchantService merchantService;
	
	@Autowired
	private ChargeAccountService chargeAccountService;
	
	@Autowired
	private AccountService accountService;
	
	@Autowired
	private LogService logService;
	
	@Autowired
	private PartnerService partnerService;
	
	@Value("${safecode}")
	private String safecode;
	
	@Value("${aes.key}")
	private String aesKey;
	
	@RequestMapping("/dayFinanceListPage.html")
    public ModelAndView dayFinanceListPage(HttpServletRequest request,HttpServletResponse response,ModelAndView mav) {
		mav.setViewName("admin/order/dayFinanceList");
		return mav;
    }
	
	@ResponseBody
	@RequestMapping(value = "/dayFinanceList.html")
	public Map dayFinanceList(HttpServletRequest req, HttpServletResponse res,int page,int limit) {
		logService.addLog(req, "查看每日流水,第"+page+"页");
		PageInfo<OrderBean> pageInfo=orderService.pageDayFinanceList(null, page, limit);
		return ResultUtil.getQuerySuccessResult(pageInfo);
	}
	
	@ResponseBody
	@RequestMapping(value = "/list.html")
	public Map list(HttpServletRequest req, HttpServletResponse res,int page,int limit,OrderBean order) {
		logService.addLog(req, "查看订单列表,第"+page+"页");
		OrderBean queryModel=new OrderBean();
		if(order.getId()!=null)queryModel.setId(order.getId());
		if(order.getMerchant_id()!=null)queryModel.setMerchant_id(order.getMerchant_id());
		if(order.getGoods_type()!=null)queryModel.setGoods_type(order.getGoods_type());
		if(order.getAmount()!=null)queryModel.setAmount(order.getAmount());
		if(!StringUtils.isEmpty(order.getPay_type()))queryModel.setPay_type(order.getPay_type());
		if(!StringUtils.isEmpty(order.getOfficial_order_no()))queryModel.setOfficial_order_no(order.getOfficial_order_no());
		if(!StringUtils.isEmpty(order.getAccount()))queryModel.setAccount(order.getAccount());
		if(!StringUtils.isEmpty(order.getCharge_account()))queryModel.setCharge_account(order.getCharge_account());
		if(!StringUtils.isEmpty(order.getMerchant_order_no()))queryModel.setMerchant_order_no(order.getMerchant_order_no());
		if(!StringUtils.isEmpty(order.getGoods_id()))queryModel.setGoods_id(order.getGoods_id());
		if(order.getStatus()!=null)queryModel.setStatus(order.getStatus());
		if(order.getNotify_status()!=null)queryModel.setNotify_status(order.getNotify_status());
		PageInfo<OrderBean> pageInfo=orderService.pageList(queryModel, page, limit);
		return ResultUtil.getQuerySuccessResult(pageInfo);
	}
	
	
	@RequestMapping("/listPage.html")
    public ModelAndView listPage(HttpServletRequest request,HttpServletResponse response,ModelAndView mav) {
		mav.addObject("leftAmount", chargeAccountService.getLeftAmount());
		mav.addObject("merchants", merchantService.queryAll());
		mav.setViewName("admin/order/list");
		return mav;
    }
	
	@RequestMapping("/detailPage.html")
    public ModelAndView detailPage(HttpServletRequest request,HttpServletResponse response,ModelAndView mav,Long accountId,Long orderId) {
		logService.addLog(request, "查单,订单号:"+orderId);
		AccountBean account=accountService.getById(accountId);
		OrderBean order=orderService.getById(orderId);
		String msg="";
		try {
			if(account==null)
			{
				msg="购买账号不存在，查询失败！";
			}
			else
			{
				OrderServiceImpl.lastActiveTime=System.currentTimeMillis()/1000;
				PlatformInterface inf=(PlatformInterface) SpringUtil.getBean(account.getOperator()+"Util");
				Map<String,String> resultMap=inf.orderDetail(order,account,GlobalConfig.notify_type);
	        	String status=resultMap.get("status");
	        	//String orderNo=resultMap.get("orderNo");
				if("success".equals(status))
					msg="订单支付成功！";
				else
					msg="订单未支付！";
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			msg=e.getMessage();
			if(e.getMessage().contains("网络链接失败"))
 			{
 				accountService.addProxyFailTimes(account.getId());
 			}
		}
		AccountBean updateAccount=new AccountBean();
		updateAccount.setId(accountId);
		updateAccount.setBuy_last_time(System.currentTimeMillis()/1000);
		accountService.update(updateAccount);
		mav.addObject("msg", msg);
		mav.setViewName("admin/order/detail");
		return mav;
    }

	
	@ResponseBody
	@RequestMapping(value = "/allNotify.html")
	public Result allNotify(HttpServletRequest req, HttpServletResponse res) {
		Result result=new Result();
		try {
			OrderBean queryModel=new OrderBean();
			queryModel.setStatus(1);
			queryModel.setNotify_status(0);
			List<OrderBean> orders=orderService.queryList(queryModel);
			for (OrderBean o : orders) {
				orderService.payNotify(o.getId(),null,2);
			}
			result.setCode(0);
			result.setMsg("操作成功,执行"+orders.size()+"条");
			return result;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			result.setCode(500);
			result.setMsg(e.getMessage());
			return result;
		}

	}
	
	@ResponseBody
	@RequestMapping(value = "/notify.html")
	public Result callback(HttpServletRequest req, HttpServletResponse res,Long orderId,String password) {
		logService.addLog(req, "补单,系统订单号:"+orderId);
		Result result=new Result();
		if(orderId==null)
		{
			result.setCode(0);
			result.setMsg("参数异常");
			return result;
		}
		if(!safecode.equals(password))
		{
			result.setCode(0);
			result.setMsg("超级密码错误");
			return result;
		}
		try {
			if(!orderService.payNotify(orderId,null,2))
			{
				result.setCode(1);
				result.setMsg("回调失败");
				return result;
			}
			OrderBean order=orderService.getById(orderId);
			if(order.getStatus()==0)
			{
				accountService.addBuyCount(order.getAccount_id());
	    		chargeAccountService.procesSuccOrder(order.getCharge_account_id());
	    		ChargeAccountBean chargeAccount=chargeAccountService.getById(order.getCharge_account_id());
	    		partnerService.subQuota(order.getPartner_id(), order.getAmount(),order.getOfficial_order_no());
			}
			result.setCode(0);
			result.setMsg("操作成功");
			return result;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			result.setCode(500);
			result.setMsg(e.getMessage());
			return result;
		}
	}
	
	@RequestMapping({ "/notGetCdkListPage.html" })
    public ModelAndView notGetCdkListPage(HttpServletRequest request, HttpServletResponse response, ModelAndView mav) {
        mav.setViewName("admin/order/notGetCdkList");
        return mav;
    }
	
	@ResponseBody
    @RequestMapping("/notGetCdkList.html")
    public Map notGetCdkList(HttpServletRequest req, HttpServletResponse res, int page, int limit, OrderBean order) {
        OrderBean queryModel = new OrderBean();
        if (order.getId() != null) {
            queryModel.setId(order.getId());
        }
        if (order.getAmount() != null) {
            queryModel.setAmount(order.getAmount());
        }
        if (!StringUtils.isEmpty(order.getPay_type())) {
            queryModel.setPay_type(order.getPay_type());
        }
        if (!StringUtils.isEmpty(order.getAccount())) {
            queryModel.setAccount(order.getAccount());
        }
        PageInfo<OrderBean> pageInfo = this.orderService.notGetCdkPageList(queryModel, page, limit);
        return ResultUtil.getQuerySuccessResult(pageInfo);
    }
}
